@model object
@{
    ViewBag.Title = "数据可视化与统计分析";
    Layout = "_Layout";
}

<div>
    <!-- 体重趋势主图 -->
    <el-card>
        <template #header>
            <div class="clearfix">
                <span>体重趋势主图</span>
                <div style="float: right;">
                    <el-button-group>
                        <el-button v-for="days in timeRanges"
                                   :key="days.value"
                                   :type="currentDays === days.value ? 'primary' : 'default'"
                                   :plain="currentDays !== days.value"
                                   size="small"
                                   @@click="changeTimeRange(days.value)">
                            {{ days.label }}
                        </el-button>
                    </el-button-group>
                    <el-button-group style="margin-left: 10px;">
                        <el-button v-for="meridiem in meridiemOptions"
                                   :key="meridiem.value"
                                   :type="currentMeridiem === meridiem.id ? 'success' : 'default'"
                                   :plain="currentMeridiem !== meridiem.id"
                                   size="small"
                                   @@click="changeMeridiem(meridiem.id)">
                            {{ meridiem.name }}
                        </el-button>
                    </el-button-group>
                </div>
            </div>
        </template>
        <div ref="weightTrendChart" style="height:350px;margin-top:15px;"></div>
    </el-card>

    <!-- 数据卡片行 -->
    <el-row :gutter="20" style="margin-top: 20px;">
        <!-- 当前数据快照 -->
        <el-col :span="12">
            <el-card shadow="hover">
                <template #header>
                    <div>
                        <span>当前数据快照</span>
                    </div>
                </template>
                <el-row :gutter="10">
                    <el-col :span="12" class="text-center">
                        <div class="text-gray text-sm">当前体重</div>
                        <div class="text-2xl font-bold mt-1">{{ currentSnapshot.currentWeight || '--' }}</div>
                        <div class="text-gray text-xs mt-1">{{ formatDate(currentSnapshot.currentWeightTime) || '暂无数据' }}</div>
                    </el-col>
                    <el-col :span="12" class="text-center">
                        <div class="text-gray text-sm">体脂率</div>
                        <div class="text-2xl font-bold mt-1">{{ currentSnapshot.bodyFat ? currentSnapshot.bodyFat + '%' : '--' }}</div>
                        <div class="text-gray text-xs mt-1">如有记录</div>
                    </el-col>
                </el-row>
            </el-card>
        </el-col>

        <!-- 周期性变化 -->
        <el-col :span="12">
            <el-card shadow="hover">
                <template #header>
                    <div>
                        <span>周期性变化</span>
                    </div>
                </template>
                <el-row :gutter="10">
                    <el-col :span="12" class="text-center">
                        <div class="text-gray text-sm">相比上周</div>
                        <div class="text-2xl font-bold mt-1">{{ formatWeightChange(periodicChange.weeklyChange) }}</div>
                        <div class="text-gray text-xs mt-1">{{ periodicChange.weeklyChangeDate ? '比较日期：' + formatDate(periodicChange.weeklyChangeDate) : '暂无数据' }}</div>
                    </el-col>
                    <el-col :span="12" class="text-center">
                        <div class="text-gray text-sm">相比上月</div>
                        <div class="text-2xl font-bold mt-1">{{ formatWeightChange(periodicChange.monthlyChange) }}</div>
                        <div class="text-gray text-xs mt-1">{{ periodicChange.monthlyChangeDate ? '比较日期：' + formatDate(periodicChange.monthlyChangeDate) : '暂无数据' }}</div>
                    </el-col>
                </el-row>
            </el-card>
        </el-col>
    </el-row>

    <!-- 第二行卡片 -->
    <el-row :gutter="20" style="margin-top: 20px;">
        <!-- 历史极值 -->
        <el-col :span="12">
            <el-card shadow="hover">
                <template #header>
                    <div>
                        <span>历史极值</span>
                    </div>
                </template>
                <el-row :gutter="10">
                    <el-col :span="12" class="text-center">
                        <div class="text-gray text-sm">历史最高体重</div>
                        <div class="text-2xl font-bold mt-1">{{ weightExtremes.maxWeight || '--' }}</div>
                        <div class="text-gray text-xs mt-1">{{ formatDate(weightExtremes.maxWeightTime) || '暂无数据' }}</div>
                    </el-col>
                    <el-col :span="12" class="text-center">
                        <div class="text-gray text-sm">历史最低体重</div>
                        <div class="text-2xl font-bold mt-1">{{ weightExtremes.minWeight || '--' }}</div>
                        <div class="text-gray text-xs mt-1">{{ formatDate(weightExtremes.minWeightTime) || '暂无数据' }}</div>
                    </el-col>
                </el-row>
            </el-card>
        </el-col>

        <!-- 累计变化 -->
        <el-col :span="12">
            <el-card shadow="hover">
                <template #header>
                    <div>
                        <span>累计变化</span>
                    </div>
                </template>
                <el-row :gutter="10">
                    <el-col :span="12" class="text-center">
                        <div class="text-gray text-sm">累计变化总量</div>
                        <div class="text-2xl font-bold mt-1">{{ formatWeightChange(changeRate.totalChange) }}</div>
                        <div class="text-gray text-xs mt-1">{{ changeRate.totalDays ? `记录 ${Math.round(changeRate.totalDays)} 天` : '暂无数据' }}</div>
                    </el-col>
                    <el-col :span="12" class="text-center">
                        <div class="text-gray text-sm">平均每周变化</div>
                        <div class="text-2xl font-bold mt-1">{{ formatWeightChange(changeRate.avgWeeklyChange) }}</div>
                        <div class="text-gray text-xs mt-1">相比初始体重</div>
                    </el-col>
                </el-row>
            </el-card>
        </el-col>
    </el-row>

    <!-- 时段数据对比分析 -->
    <el-card style="margin-top: 20px;">
        <template #header>
            <div>
                <span>时段数据对比分析</span>
            </div>
        </template>
        <el-row :gutter="10">
            <el-col :span="8" class="text-center">
                <div class="text-gray text-sm">早晨数据</div>
                <div class="text-2xl font-bold mt-1">{{ periodStats.morning.averageWeight ? periodStats.morning.averageWeight.toFixed(1) + ' kg' : '--' }}</div>
                <div class="text-sm mt-1">{{ formatWeightChange(periodStats.morning.totalChange) }}</div>
            </el-col>
            <el-col :span="8" class="text-center">
                <div class="text-gray text-sm">中午数据</div>
                <div class="text-2xl font-bold mt-1">{{ periodStats.noon.averageWeight ? periodStats.noon.averageWeight.toFixed(1) + ' kg' : '--' }}</div>
                <div class="text-sm mt-1">{{ formatWeightChange(periodStats.noon.totalChange) }}</div>
            </el-col>
            <el-col :span="8" class="text-center">
                <div class="text-gray text-sm">晚上数据</div>
                <div class="text-2xl font-bold mt-1">{{ periodStats.evening.averageWeight ? periodStats.evening.averageWeight.toFixed(1) + ' kg' : '--' }}</div>
                <div class="text-sm mt-1">{{ formatWeightChange(periodStats.evening.totalChange) }}</div>
            </el-col>
        </el-row>
    </el-card>
</div>

@section Scripts {
    <script src="~/js/echarts.min.js"></script>
    <script>
        // 创建Vue实例
        var statisticsApp = new Vue({
            el: '#app',
            mixins: [curdMixin],
            data: {
                // 图表实例
                weightChart: null,
                // 筛选条件
                currentDays: 30,
                currentMeridiem: null,
                // 时间范围选项
                timeRanges: [
                    { value: 7, label: '最近7天' },
                    { value: 30, label: '最近30天' },
                    { value: 90, label: '最近3个月' },
                    { value: 365, label: '全年' }
                ],
                // 时段选项
                meridiemOptions: [],
                // 数据
                weightTrendData: [],
                currentSnapshot: {
                    currentWeight: null,
                    currentWeightTime: null,
                    bodyFat: null
                },
                periodicChange: {
                    weeklyChange: null,
                    weeklyChangeDate: null,
                    monthlyChange: null,
                    monthlyChangeDate: null
                },
                weightExtremes: {
                    maxWeight: null,
                    maxWeightTime: null,
                    minWeight: null,
                    minWeightTime: null
                },
                changeRate: {
                    totalChange: null,
                    totalDays: null,
                    avgWeeklyChange: null
                },
                periodStats: {
                    morning: { averageWeight: null, totalChange: null },
                    noon: { averageWeight: null, totalChange: null },
                    evening: { averageWeight: null, totalChange: null }
                }
            },
            mounted: function() {
                 this.loadMerdiem();
                // 初始化图表
                this.weightChart = echarts.init(this.$refs.weightTrendChart);

                // 初始加载数据
                this.loadAllData();

                // 窗口大小改变时重绘图表
                window.addEventListener('resize', this.resizeChart);
            },
            beforeDestroy: function() {
                // 移除事件监听器
                window.removeEventListener('resize', this.resizeChart);
            },
            methods: {
                loadMerdiem:function(){
                    this.$http.get("/meridiem/list").then(response => {
                        this.meridiemOptions = [ { id: null, name: '全部时段' },...response.rows ];
                    }).catch(error => {
                        console.error('加载体重趋势数据失败:', error);
                        this.$message.error('加载体重趋势数据失败');
                    });
                },
                // 改变时间范围
                changeTimeRange: function(days) {
                    this.currentDays = days;
                    this.loadWeightTrendData();
                },
                // 改变时段筛选
                changeMeridiem: function(meridiem) {
                    this.currentMeridiem = meridiem;
                    this.loadWeightTrendData();
                },
                // 加载所有数据
                loadAllData: function() {
                    this.loadWeightTrendData();
                    this.loadCurrentSnapshot();
                    this.loadPeriodicChange();
                    this.loadWeightExtremes();
                    this.loadChangeRate();
                    this.loadPeriodSpecificStats();
                },
                // 加载体重趋势数据
                loadWeightTrendData: function() {
                    var url = '/Statistics/enhanced-trend/' + this.currentDays;
                    if (this.currentMeridiem !== null) {
                        url += '?meridiemFilter=' + this.currentMeridiem;
                    }

                    this.$http.get(url).then(response => {
                        this.weightTrendData = response;
                        this.updateWeightChart();
                    }).catch(error => {
                        console.error('加载体重趋势数据失败:', error);
                        this.$message.error('加载体重趋势数据失败');
                    });
                },
                // 更新体重趋势图表
                updateWeightChart: function() {
                    // 准备图表数据并计算最小体重值
                    var weightData = [];
                    var bodyFatData = [];
                    var minValue = Infinity;
                    
                    // 构建数据并计算最小体重值
                    this.weightTrendData.forEach(function(item) {
                        if (item.weight !== null) {
                            weightData.push([item.date, item.weight]);
                            minValue = Math.min(minValue, item.weight);
                        }
                        if (item.bodyFat !== null) {
                            bodyFatData.push([item.date, item.bodyFat]);
                        }
                    });
                    
                    // 设置y轴最小值为最小值减1，如果没有有效数据则默认为40
                    var yAxisMin = minValue === Infinity ? 40 : minValue - 1;

                    var option = {
                        // 添加背景色
                        backgroundColor: '#f7f8fa',
                        // 图表边距
                        grid: {
                            left: '3%',
                            right: '4%',
                            bottom: '3%',
                            containLabel: true
                        },
                        tooltip: {
                            trigger: 'axis',
                            backgroundColor: 'rgba(255, 255, 255, 0.95)',
                            borderColor: '#ddd',
                            borderWidth: 1,
                            textStyle: { color: '#333' },
                            formatter: function(params) {
                                var dataIndex = params[0].dataIndex;
                                var date = new Date(params[0].value[0]).toLocaleDateString();
                                var weight = params[0].value[1];
                                var change = statisticsApp.weightTrendData[dataIndex].changeFromPrevious;
                                var meridiem = statisticsApp.weightTrendData[dataIndex].meridiem;
                                var meridiemText = '';
                                if (meridiem === 1) meridiemText = '早晨';
                                else if (meridiem === 2) meridiemText = '中午';
                                else if (meridiem === 3) meridiemText = '晚上';
                                
                                var result = '<div style="font-weight: bold; margin-bottom: 5px;">日期：' + date + '</div>';
                                if (meridiemText) {
                                    result += '<div>时段：' + meridiemText + '</div>';
                                }
                                result += '<div>体重：<span style="color: #1890ff;">' + weight + ' kg</span></div>';
                                
                                if (change !== null) {
                                    var changeColor = change > 0 ? '#f5222d' : '#52c41a';
                                    result += '<div>变化：<span style="color: ' + changeColor + ';">' + 
                                              (change > 0 ? '+' : '') + change.toFixed(2) + ' kg</span></div>';
                                }
                                
                                // 查找体脂率数据
                                for (var i = 1; i < params.length; i++) {
                                    if (params[i].value && params[i].seriesName === '体脂率') {
                                        result += '<div>体脂率：<span style="color: #52c41a;">' + params[i].value[1] + '%</span></div>';
                                        break;
                                    }
                                }
                                
                                return result;
                            }
                        },
                        legend: {
                            data: ['体重', '体脂率'],
                            top: '10px',
                            textStyle: { color: '#666' }
                        },
                        xAxis: {
                            type: 'time',
                            boundaryGap: false,
                            axisLine: { lineStyle: { color: '#ddd' } },
                            axisTick: { show: false },
                            axisLabel: { color: '#666' },
                            splitLine: { 
                                show: true, 
                                lineStyle: { 
                                    color: '#f0f0f0',
                                    type: 'dashed'
                                }
                            }
                        },
                        yAxis: [
                            {
                                type: 'value',
                                name: '体重 (kg)',
                                position: 'left',
                                min: yAxisMin,
                                axisLine: { lineStyle: { color: '#1890ff' } },
                                axisTick: { show: false },
                                axisLabel: { color: '#666' },
                                splitLine: { 
                                    show: true, 
                                    lineStyle: { 
                                        color: '#f0f0f0',
                                        type: 'dashed'
                                    }
                                }
                            },
                            {
                                type: 'value',
                                name: '体脂率 (%)',
                                position: 'right',
                                axisLine: { lineStyle: { color: '#52c41a' } },
                                axisTick: { show: false },
                                axisLabel: { color: '#666' },
                                splitLine: { show: false }
                            }
                        ],
                        series: [
                            {
                                name: '体重',
                                type: 'line',
                                data: weightData,
                                smooth: true,
                                connectNulls: true,
                                symbol: 'circle',
                                symbolSize: 6,
                                lineStyle: {
                                    color: '#1890ff',
                                    width: 3
                                },
                                areaStyle: {
                                    color: {
                                        type: 'linear',
                                        x: 0, y: 0, x2: 0, y2: 1,
                                        colorStops: [
                                            { offset: 0, color: 'rgba(24, 144, 255, 0.3)' },
                                            { offset: 1, color: 'rgba(24, 144, 255, 0.05)' }
                                        ]
                                    }
                                },
                                itemStyle: {
                                    color: '#1890ff',
                                    borderColor: '#fff',
                                    borderWidth: 2
                                },
                                emphasis: {
                                    itemStyle: {
                                        color: '#1890ff',
                                        borderColor: '#fff',
                                        borderWidth: 3,
                                        shadowBlur: 10,
                                        shadowColor: 'rgba(24, 144, 255, 0.5)'
                                    },
                                    symbolSize: 10
                                }
                            }
                        ]
                    };

                    // 如果有体脂率数据，添加第二个系列
                    if (bodyFatData.length > 0) {
                        option.series.push({
                            name: '体脂率',
                            type: 'line',
                            yAxisIndex: 1,
                            data: bodyFatData,
                            smooth: true,
                            connectNulls: true,
                            symbol: 'circle',
                            symbolSize: 6,
                            lineStyle: {
                                color: '#52c41a',
                                width: 2,
                                type: 'dashed'
                            },
                            itemStyle: {
                                color: '#52c41a',
                                borderColor: '#fff',
                                borderWidth: 2
                            },
                            emphasis: {
                                itemStyle: {
                                    color: '#52c41a',
                                    borderColor: '#fff',
                                    borderWidth: 3,
                                    shadowBlur: 10,
                                    shadowColor: 'rgba(82, 196, 26, 0.5)'
                                },
                                symbolSize: 10
                            }
                        });
                    }

                    this.weightChart.setOption(option);
                },
                // 加载当前数据快照
                loadCurrentSnapshot: function() {
                    this.$http.get('/Statistics/current-snapshot').then(response => {
                        this.currentSnapshot = response;
                    }).catch(error => {
                        console.error('加载当前数据快照失败:', error);
                        this.$message.error('加载当前数据快照失败');
                    });
                },
                // 加载周期性变化
                loadPeriodicChange: function() {
                    this.$http.get('/Statistics/periodic-change').then(response => {
                        this.periodicChange = response;
                    }).catch(error => {
                        console.error('加载周期性变化数据失败:', error);
                        this.$message.error('加载周期性变化数据失败');
                    });
                },
                // 加载历史极值
                loadWeightExtremes: function() {
                    this.$http.get('/Statistics/extremes').then(response => {
                        this.weightExtremes = response;
                    }).catch(error => {
                        console.error('加载历史极值数据失败:', error);
                        this.$message.error('加载历史极值数据失败');
                    });
                },
                // 加载累计变化
                loadChangeRate: function() {
                    this.$http.get('/Statistics/change-rate').then(response => {
                        this.changeRate = response;
                    }).catch(error => {
                        console.error('加载累计变化数据失败:', error);
                        this.$message.error('加载累计变化数据失败');
                    });
                },
                // 加载时段特定统计
                loadPeriodSpecificStats: function() {
                    // 加载早晨数据
                    this.$http.get('/Statistics/period-specific/1').then(response => {
                        this.periodStats.morning = response;
                    }).catch(error => {
                        console.error('加载早晨数据失败:', error);
                        this.$message.error('加载早晨数据失败');
                    });

                    // 加载中午数据
                    this.$http.get('/Statistics/period-specific/2').then(response => {
                        this.periodStats.noon = response;
                    }).catch(error => {
                        console.error('加载中午数据失败:', error);
                        this.$message.error('加载中午数据失败');
                    });

                    // 加载晚上数据
                    this.$http.get('/Statistics/period-specific/3').then(response => {
                        this.periodStats.evening = response;
                    }).catch(error => {
                        console.error('加载晚上数据失败:', error);
                        this.$message.error('加载晚上数据失败');
                    });
                },
                // 格式化日期
                formatDate: function(dateString) {
                    if (!dateString) return null;
                    return new Date(dateString).toLocaleDateString();
                },
                // 格式化体重变化
                formatWeightChange: function(change) {
                    if (!change && change !== 0) return '--';
                    return (change > 0 ? '+' : '') + change.toFixed(2) + ' kg';
                },
                // 重绘图表
                resizeChart: function() {
                    if (this.weightChart) {
                        this.weightChart.resize();
                    }
                },
                // 所有网络请求已使用this.$http.get替代
            }
        });
    </script>
}